import os
from urllib.parse import quote
from pypinyin import lazy_pinyin
from flask import jsonify, make_response, abort, request, Response
from flask_restful import Resource

import dataresource
from models.model import Shulj, db
from redisUtil import rs
from schemas import ShuljSchema
from test import apiModel
from tasks import show, add


@apiModel.route('/set_cookie')
@dataresource.robust
def set_cookie():
    res = make_response('OK')
    res.set_cookie("name", "123")
    return res


@apiModel.route('/shulj', methods=['GET'])
@dataresource.robust
def getShulj():
    # 获取cookie的值
    print(request.cookies.get('name'))
    schema = ShuljSchema()
    shulj = Shulj.query.all()
    data = schema.dump(shulj, many=True)
    return jsonify({'res': data}), 200
    # templates-HTML模板jinja
    # return render_template('test.html', name=str(data))


# 新增
@apiModel.route('/shulj', methods=['POST'])
@dataresource.robust
def addShulj():
    json_data = request.get_data()
    import json
    res = json.loads(json_data.decode('utf-8'))
    shulj1 = Shulj(name=res.get('name'), sex=res.get('sex'), age=res.get('age'))
    db.session.add(shulj1)
    db.session.commit()
    return jsonify({'res': True}), 200


# 修改
@apiModel.route('/shulj', methods=['PATCH'])
@dataresource.robust
def updataShulj():
    try:
        shulj = Shulj.query.filter(Shulj.id == 100).first()
        # if shulj:
        shulj.name = 'shulujie'
        db.session.commit()
        return jsonify({'res': True}), 200
    except Exception as e:
        abort(500)
        return jsonify({'res': False, 'message': str(e)})


@apiModel.route('/shulj', methods=['DELETE'])
@dataresource.robust
def deleteShulj():
    try:
        shulj = Shulj.query.filter(Shulj.id == 100).first()
        db.session.delete(shulj)
        db.session.commit()
        return jsonify({'res': True}), 200
    except Exception as e:
        abort(500)
        return jsonify({'res': False, 'message': str(e)})


# restful规范
class HelloWorld1(Resource):
    def get(self, hello_id):
        return {'hello1': hello_id}


class HelloWorld2(Resource):
    def get(self, hello_id):
        return {'hello2': hello_id}


# 文件下载
@apiModel.route('/downloadfile/', methods=['GET', 'POST'])
def downloadfile():
    if request.method == 'GET':
        fullfilename = request.args.get('filename')
        fullfilenamelist = fullfilename.split('/')
        filename = fullfilenamelist[-1]

        def send_file():
            store_path = fullfilename
            with open(store_path, 'rb') as targetfile:
                while 1:
                    data = targetfile.read(20 * 1024 * 1024)  # 每次读取20M
                    if not data:
                        break
                    yield data

        response = Response(send_file(), content_type='application/octet-stream')
        # 如果不加上这行代码，导致问题
        response.headers["Content-Disposition"] = "attachment; filename={0}; filename*=utf-8''{0}".format(
            quote(filename))
        return response


# 设置允许上传的文件类型
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg'])

# 设置上传文件存放的目录
UPLOAD_FOLDER = 'D:/flaskTest/uploads'


# 检查文件类型是否合法
def allowed_file(filename):
    # 判断文件的扩展名是否在配置项ALLOWED_EXTENSIONS中
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


# 文件上传
# 最好新建个表，在表中存入原来的中文名和转拼音后的filename，在下载文件时再把中文名赋值给filename
@apiModel.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # 获取上传过来的文件对象
        file = request.files['file']
        # 检查文件对象是否存在，且文件名合法
        if file and allowed_file(file.filename):
            # 去除文件名中不合法的内容
            # filename = secure_filename(file.filename)
            # 文件名中文转拼音
            filename = "".join(lazy_pinyin(file.filename))
            # 将文件保存在本地UPLOAD_FOLDER目录下
            file.save(os.path.join(UPLOAD_FOLDER, filename))
            return 'Upload Successfully'
        else:  # 文件不合法
            return 'Upload Failed'
    else:  # GET方法
        return 'method is GET'


@apiModel.route("/task")
def task():
    """一个测试的实例"""
    add.delay()
    return '正在执行task'


@apiModel.route("/task1")
def task1():
    """一个测试的实例"""
    show.delay()
    return '正在执行task1'


# redis获取数据
@apiModel.route("/task_result")
def task_result():
    redis_result = rs.get('celery-task-meta-df3e1a9d-dcd2-4cc2-bcd7-51c4ac083fe7')
    import json
    res = json.loads(redis_result)
    return str(res.get('result'))
